package com.jintian.smart.kernel.orm.mapper.internal;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.jintian.smart.kernel.core.exception.BeetlSQLExceptionCode;
import org.beetl.sql.clazz.ClassDesc;
import org.beetl.sql.clazz.kit.BeetlSQLException;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.query.LambdaQuery;
import org.beetl.sql.mapper.MapperInvoke;

public class UpdateTemplate2AMI extends MapperInvoke {
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public Object call(SQLManager sm, Class entityClass, Method m, Object[] args) {
        Map<String, Object> template2 = (Map<String, Object>) args[0];
        ClassDesc desc = sm.getClassDesc(entityClass);
        String versionAttr = desc.getClassAnnotation().getVersionProperty();
        if (versionAttr != null && template2.get(versionAttr) == null) {
            throw new BeetlSQLException(BeetlSQLExceptionCode.NEED_VERSION_ATTR.getCode(),
                    BeetlSQLExceptionCode.NEED_VERSION_ATTR.getMsg());
        }

        LambdaQuery query = sm.lambdaQuery(entityClass);
        List<String> ids = desc.getIdAttrs();

        for (Entry<String, Object> e : template2.entrySet()) {
            String colName = sm.getNc().getColName(e.getKey());
            Object value = e.getValue();
            if (ids.contains(e.getKey())) {
                // where key=value
                query.andEq(colName, value);
            } else {
                if (e.getKey().equals(versionAttr)) {
                    // set version = version + 1
                    query.set(colName, ((Number) value).intValue() + 1);
                    // 乐观锁 where version=value
                    query.andEq(colName, value);
                } else {
                    // set column = value
                    query.set(colName, value);
                }
            }
        }
        return query.update() == 1;
    }
}
